package com.application.module.couponget;

import com.application.intercept.BaseInterceptor;
import com.application.model.Global;
import com.application.module.share.Share;
import com.jfinal.aop.Invocation;
import com.platform.mvc.user.User;
import org.apache.log4j.Logger;

import java.util.List;

public class ShareCouponGetInterceptor extends BaseInterceptor {

    private static Logger log = Logger.getLogger(ShareCouponGetInterceptor.class);


    @Override
    protected void handler(Invocation invoc) {

    }

    @Override
    protected void success(User user) {
        Integer userid = user.getId();

        giftUnlock(userid);
        giftPlay(userid);
    }


    private void giftUnlock(Integer userid) {
        List<Share> list = Share.dao.findAvailable(userid);
        String value = Global.cacheGetByCode(Global.Code.gift_share).getValue();
        String[] split = value.split("/");
        try {
            if (list.size() >= Integer.parseInt(split[0])) {
                list.forEach(o -> o.set("used", 1).update());
                int amount = Integer.parseInt(split[1]);
                CouponGet.dao.add(CouponGet.SOURCE_SHARE, CouponGet.TYPE_UNLOCK, amount, userid);
            }
        } catch (Exception e) {
            log.error("######分享赠送优惠券未配置");
        }
    }

    private void giftPlay(Integer userid) {
        List<Share> list = Share.dao.findAvailablePlay(userid);
        String value = Global.cacheGetByCode(Global.Code.gift_sharePlay).getValue();
        String[] split = value.split("/");
        try {
            if (list.size() >= Integer.parseInt(split[0])) {
                list.forEach(o -> o.set("used2", 1).update());
                int amount = Integer.parseInt(split[1]);
                CouponGet.dao.add(CouponGet.SOURCE_SHARE, CouponGet.TYPE_PLAY, amount, userid);
            }
        } catch (Exception e) {
            log.error("######分享赠送优惠券未配置");
        }
    }
}
